package com.huike.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.huike.business.pojos.ClientInfo;
import com.huike.clue.pojos.Clue;
import com.huike.contract.pojos.ContractList;
import com.huike.mapper.*;
import com.huike.report.vos.*;
import com.huike.result.Result;
import com.huike.service.ReportService;
import com.huike.user.pojos.User;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl  implements ReportService {

    @Autowired
    private ClueMapper clueMapper;
    @Autowired
    private ClientInfoMapper clientInfoMapper;
    @Autowired
    private ContractListMapper contractListMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private BranchMapper branchMapper;
    /**
     * 基础数据查询
     * @param begin
     * @param end
     * @return
     */
    @Override
    public Result findBaseData(String begin, String end) {
        //校验参数
        if (begin==null || end==null){
            return Result.error("参数异常");
        }
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-M-d");
        LocalDateTime beginTime = LocalDateTime.of(LocalDate.parse(begin, formatter), LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(LocalDate.parse(end, formatter), LocalTime.MAX);
        BaseDataVO baseDataVO= new BaseDataVO();

        //查询线索数量
        LambdaQueryWrapper<Clue> clueLQW=new LambdaQueryWrapper<Clue>().ge(Clue::getCreateTime,beginTime).le(Clue::getCreateTime,endTime);
        baseDataVO.setClueCount(clueMapper.selectCount(clueLQW).intValue());
        //查询商机数量
        LambdaQueryWrapper<ClientInfo> lqw=new LambdaQueryWrapper<ClientInfo>().ne(ClientInfo::getClientStatus,5).ge(ClientInfo::getCreateTime,beginTime).le(ClientInfo::getCreateTime,endTime);
        baseDataVO.setBusinessCount(clientInfoMapper.selectCount(lqw).intValue());
        //查询客户数量
        LambdaQueryWrapper<ClientInfo> clientInfoLqw=new LambdaQueryWrapper<ClientInfo>().eq(ClientInfo::getClientStatus,5).ge(ClientInfo::getCreateTime,beginTime).le(ClientInfo::getCreateTime,endTime);
        baseDataVO.setCustomCount(clientInfoMapper.selectCount(clientInfoLqw).intValue());
        //查询金额
        double aslesAmount=0.00;
        LambdaQueryWrapper<ContractList> contractListLQW=new LambdaQueryWrapper<ContractList>().ge(ContractList::getCreatedTime,beginTime).le(ContractList::getCreatedTime,endTime);
        List<ContractList> contractLists = contractListMapper.selectList(contractListLQW);
        for (ContractList contractList : contractLists) {
            aslesAmount+=contractList.getContractPrice();
        }
        double newAslesAmount = Math.round(aslesAmount * 100) / 100.00;
        baseDataVO.setAslesAmount(newAslesAmount);
        return Result.success(baseDataVO);
    }

    /**
     * 今日简报查询
     * @return
     */
    @Override
    public Result findTodayBriefing() {
        LocalDate now = LocalDate.now();
        //一天的开始时间
        LocalDateTime startTime = LocalDateTime.of(now, LocalTime.MIN);
        //一天的结束时间
        LocalDateTime endTime = LocalDateTime.of(now, LocalTime.MAX);
        //查询今日新增线索
        LambdaQueryWrapper<Clue> clueLqw=new LambdaQueryWrapper<>();
        clueLqw.ge(Clue::getCreateTime,startTime).le(Clue::getCreateTime,endTime);
        int addClue = clueMapper.selectCount(clueLqw).intValue();
        //查询今日新增商机
        LambdaQueryWrapper<ClientInfo>  businessLqw=new LambdaQueryWrapper<>();
        businessLqw.ge(ClientInfo::getCreateTime,startTime).le(ClientInfo::getCreateTime,endTime).ne(ClientInfo::getClientStatus,5);
        int business = clientInfoMapper.selectCount(businessLqw).intValue();
        //查询今日新增客户
        LambdaQueryWrapper<ClientInfo>  clientInfoLqw=new LambdaQueryWrapper<>();
        clientInfoLqw.ge(ClientInfo::getCreateTime,startTime).le(ClientInfo::getCreateTime,endTime).eq(ClientInfo::getClientStatus,5);
        int addClientInfo = clientInfoMapper.selectCount(clientInfoLqw).intValue();
        //查询今日新增客户
        double addSales=0.00;
        LambdaQueryWrapper<ContractList> contractListLqw=new LambdaQueryWrapper<ContractList>().ge(ContractList::getCreatedTime,startTime).le(ContractList::getCreatedTime,endTime);
        List<ContractList> contractLists = contractListMapper.selectList(contractListLqw);
        for (ContractList contractList : contractLists) {
            addSales+=contractList.getContractPrice();
        }
        double newAddSales = Math.round(addSales * 100) / 100.00;
        //封装vo返回
        TodayBriefingVO todayBriefingVO= createTodayBriefingVO(addClue,business,addClientInfo,newAddSales);
        return Result.success(todayBriefingVO);
    }

    private TodayBriefingVO createTodayBriefingVO(int addClue, int business, int addClientInfo, double newAddSales) {
        TodayBriefingVO vo=new TodayBriefingVO();
        vo.setAddClues(addClue);
        vo.setAddBusiness(business);
        vo.setAddCustom(addClientInfo);
        vo.setAddSales(newAddSales);
        return vo;
    }

    /**
     * 待办事项
     *
     * @return
     */
    @Override
    public Result toDoList() {
        ToDoListVO toDoListVO = new ToDoListVO();
        //待跟进线索
        toDoListVO.setTreatFollowUpClues(clueMapper.selectCount(
                new LambdaQueryWrapper<Clue>().eq(Clue::getClueStatus, 2)).intValue());
        //待跟进商机
        toDoListVO.setTreatFollowUpCustom(clientInfoMapper.selectCount(
                new LambdaQueryWrapper<ClientInfo>().eq(ClientInfo::getClientStatus,2)).intValue());
        //待分配线索
        toDoListVO.setTreatAllocationClues(clueMapper.selectCount(
                new LambdaQueryWrapper<Clue>().eq(Clue::getClueStatus,3)).intValue());
        //待分配商机
        toDoListVO.setTreatAllocationCustom(clientInfoMapper.selectCount(
                new LambdaQueryWrapper<ClientInfo>().eq(ClientInfo::getClientStatus,1)).intValue());
        return Result.success(toDoListVO);
    }

    @Override
    public Result clueConvert(String begin, String end) {
        //校验参数
        if (begin==null || end==null){
            return Result.error("参数异常");
        }
        Result result = findBaseData(begin, end);
        BaseDataVO baseDataVO = (BaseDataVO)result.getData();
        //构建FunnelVO返回
        FunnelVO funnelVO=createFunnelVO(baseDataVO);
        return Result.success(funnelVO);
    }

    private FunnelVO createFunnelVO(BaseDataVO baseDataVO) {
        //线索总数
        Integer clueCount = baseDataVO.getClueCount();
        //客户数
        Integer customCount = baseDataVO.getCustomCount();
        //商机数
        Integer businessCount = baseDataVO.getBusinessCount();
        //有效线索数
        LambdaQueryWrapper<Clue> clueLwq=new LambdaQueryWrapper<>();
        clueLwq.eq(Clue::getTrueOrFalseClues,0);
        int clueEffective = clueMapper.selectCount(clueLwq).intValue();
        FunnelVO funnelVO=new FunnelVO(clueCount,clueEffective,businessCount,customCount);
        return funnelVO;
    }
    /**
     * 线索龙虎榜
     * @param begin
     * @param end
     * @return
     */
    @Override
    public Result clueList(String begin, String end) {
        //校验参数
        if (begin == null || end == null) {
            return Result.error("参数异常");
        }
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-M-d");
        LocalDateTime beginTime = LocalDateTime.of(LocalDate.parse(begin, formatter), LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(LocalDate.parse(end, formatter), LocalTime.MAX);

        List<Clue> clues = clueMapper.selectList(new LambdaQueryWrapper<Clue>()
                .gt(Clue::getCreateTime, beginTime).lt(Clue::getCreateTime, endTime));

        List<Integer> userIds =clues.stream().map(Clue::getUserId).distinct().collect(Collectors.toList());

        List<ClueListVO> clueListVOS = new ArrayList<>();

        for (Integer userId : userIds) {
            ClueListVO clueListVO = new ClueListVO();
            //根据id查询归属线索总数
            Long clueCount = clues.stream().filter(clue -> clue.getUserId() == userId).count();

            //根据id查询已转换,已完成
            Long count = clues.stream().filter(clue -> clue.getUserId() == userId).filter(clue -> clue.getClueStatus()==4).count();
            int clueEffective = count.intValue();
            //计算转换率
            if (clueCount == 0) {
                return Result.error("没有数据");
            }
            double clueConversionRate = clueEffective / (clueCount * 1.00);
            clueConversionRate= Math.round(clueConversionRate*100)/100.00;
            //查询部门
            User user = userMapper.selectById(userId);

            //封装排行
            clueListVO.setName(user.getName());
            clueListVO.setClueEffective(clueEffective);
            clueListVO.setClueConversionRate(clueConversionRate);
            clueListVO.setBranchName(user.getBranchName());
            clueListVOS.add(clueListVO);
        }
        List<ClueListVO> list = clueListVOS.stream().sorted(Comparator.comparing(ClueListVO::getClueConversionRate)).collect(Collectors.toList());
        return Result.success(list);
    }

    /**
     * 商机龙虎榜
     * @param begin
     * @param end
     * @return
     */
    @Override
    public Result businessList(String begin, String end) {
        //校验参数
        if (begin==null || end==null){
            return Result.error("参数异常");
        }
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-M-d");
        LocalDateTime beginTime = LocalDateTime.of(LocalDate.parse(begin, formatter), LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(LocalDate.parse(end, formatter), LocalTime.MAX);

        LambdaQueryWrapper<ClientInfo> clientInfoLqw=new LambdaQueryWrapper<>();
        clientInfoLqw.ge(ClientInfo::getCreateTime,beginTime).le(ClientInfo::getCreateTime,endTime);
        List<ClientInfo> clientInfos = clientInfoMapper.selectList(clientInfoLqw);
        List<Integer> userIds = clientInfos.stream().map(ClientInfo::getSellId).distinct().collect(Collectors.toList());
        List<BusinessListVO> listVOS=new ArrayList<>();
        for (Integer userId : userIds) {
            BusinessListVO businessListVO=new BusinessListVO();
            User user = userMapper.selectById(userId);
            Long count = clientInfos.stream().filter(clientInfo -> clientInfo.getSellId() == userId).count();
            Long businnesEffective = clientInfos.stream()
                    .filter(clientInfo -> clientInfo.getSellId() == userId)
                    .filter(clientInfo -> clientInfo.getClientStatus()==5).count();
            Double businnesConversionRate=businnesEffective/(count*1.00);
            businnesConversionRate = Math.round(businnesConversionRate * 100) / 100.00;
            businessListVO.setBusinnesEffective(businnesEffective.intValue());
            businessListVO.setBusinnesConversionRate(businnesConversionRate);

            BeanUtils.copyProperties(user,businessListVO);
            listVOS.add(businessListVO);
        }
        //排序
        List<BusinessListVO> list = listVOS.stream().sorted(Comparator.comparing(BusinessListVO::getBusinnesConversionRate)).collect(Collectors.toList());
        return Result.success(list);
    }
}
